package com.baijia.ticket.registry;

import com.baijia.ticket.Ticket;
import com.baijia.util.RedisUtil;
import com.baijia.util.SerializeUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @title TicketGrantingTicketRegistry
 * @desc Redis存粗票据
 * @author caoliang
 * @date 2015年11月10日
 * @version 1.0
 */
@Component
public final class RedisTicketRegistry implements TicketRegistry {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${passport.for_test:false}")
    private boolean isTest;

    public RedisTicketRegistry() {
    }

    /**
     * @throws ticket为空抛出IllegalArgumentException
     */
    @Override
    public void addTicket(final Ticket ticket) {
        Assert.notNull(ticket, "ticket cannot be null");
        logger.info("Added ticket [" + ticket.getId() + "] to registry. expire time:" + ticket.getExpireTime());

        RedisUtil.setex(ticket.getId().getBytes(), isTest ? 600000 : ticket.getExpireTime(),
            SerializeUtil.serialize(ticket));
    }

    @Override
    public void addTicketWithRememberMe(final Ticket ticket) {
        Assert.notNull(ticket, "ticket cannot be null");
        logger.info("Added ticket [" + ticket.getId() + "] to registry. expire time:" + ticket.getExpireTime());
        logger.info("RememberMe Expire Time : {}", ticket.getRememberMeExpireTimeExpireTime());

        RedisUtil.setex(ticket.getId().getBytes(), ticket.getRememberMeExpireTimeExpireTime(),
            SerializeUtil.serialize(ticket));
    }

    /**
     * @throws ticket为空抛出IllegalArgumentException
     */
    @Override
    public void updateTicket(final Ticket ticket) {
        Assert.notNull(ticket, "ticket cannot be null");
        logger.debug("Update ticket [{}] to registry.", ticket.getId());

        RedisUtil.setex(ticket.getId().getBytes(), isTest ? 60000 : ticket.getExpireTime(),
            SerializeUtil.serialize(ticket));
    }

    @Override
    public Ticket getTicket(final String ticketId) {
        logger.debug("Attempting to retrieve ticket [{}]", ticketId);

        if (StringUtils.isEmpty(ticketId)) {
            return null;
        }

        Ticket ticket = null;
        byte[] ticketBytes = RedisUtil.get(ticketId.getBytes());

        if (ticketBytes == null) {
            logger.debug("Ticket [{}] not found in registry.", ticketId);
        } else {
            ticket = (Ticket) SerializeUtil.unserialize(ticketBytes);
        }

        return ticket;
    }

    @Override
    public boolean deleteTicket(final String ticketId) {

        logger.debug("Removing ticket [{}] from registry", ticketId);

        if (ticketId == null) {
            return false;
        }

        return RedisUtil.del(ticketId.getBytes());
    }

}
